package adc.app.ui.wicket;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import adc.app.ui.wicket.security.ManagesDomainObject;

public class PageLink<T extends AbstractLayoutPage> extends BookmarkablePageLink<T> {

	private static final long serialVersionUID = 1L;

	public PageLink(String id, Class<T> pageClass) {
		this(id, pageClass, new PageParameters());
	}
	
	public PageLink(String id, Class<T> pageClass, PageParameters params) {
		super(id, pageClass, params);
		add(new MarkSelectedBehavior());
	}

	private static final class MarkSelectedBehavior extends AttributeAppender {

		private static final long serialVersionUID = 1L;

		private MarkSelectedBehavior() {
			super("class", true, new Model<String>("selected"), " ");
		}

		@Override
		public boolean isEnabled(Component component) {
			BookmarkablePageLink<?> link = (BookmarkablePageLink<?>) component;
			boolean samePage = link.getPageClass().isAssignableFrom(link.getPage().getClass());
			ManagesDomainObject mdoLink = link.getPageClass().getAnnotation(ManagesDomainObject.class);
			boolean sameDomainObject = false;
			if (mdoLink != null) {
				ManagesDomainObject mdoCurrent = link.getPage().getClass().getAnnotation(ManagesDomainObject.class);
				sameDomainObject = mdoCurrent != null && mdoCurrent.value().equals(mdoLink.value());
			}
			return samePage || sameDomainObject;
		}

	}
}
